<script setup>
import axios from "axios";
import { ref, onMounted, h } from "vue";
import { ElNotification } from "element-plus";
onMounted(() => {
  getUserData();
});
const getUserData = async () => {
  console.log(1);
  let { data } = await axios.get("http://localhost:3000/sayingsList");
  tableData.value = data;
  sayArr.value=data.map((item) => item.text);
  // console.log(sayArr.value);
};

const tableData = ref([]);
const sayArr = ref([]);
const deleteRow = async (index, id) => {
  // console.log(id, index);
  tableData.value.splice(index, 1);
  await axios.delete(`http://localhost:3000/sayingsList/${id}`);
  ElNotification({
    title: "提示",
    type:'info',
    message: h("i", { style: "color: red" }, `id为${id}的语录被删除`),
  });
  getUserData();
};

const text = ref("");
const onAddItem = async () => {
  if (!text.value.trim()) {
    ElNotification({
      title: "提示",
      type: "warning",
      message: h("i", { style: "color: red" }, "请输入你要添加的语录"),
    });
    return;
  }
  const textArr = text.value.split("/").map((item) => item.trim().replace(/\n/g, ""));
  const filterArr = textArr.filter((item) => !sayArr.value.includes(item));
  console.log(filterArr)
  if (filterArr.length == 0) {
    ElNotification({
      title: "提示",
      type: "info",
      message: h("i", { style: "color: orange" }, "没有新语录需要添加"),
    });
    return;
  }

  for (const item of filterArr) {
    await axios.post("http://localhost:3000/sayingsList", { text: item });
  }
  ElNotification({
    title: "提示",
    type: "success",
    message: h("i", { style: "color: green" }, "添加成功"),
  });
  text.value = "";
  getUserData();
};
</script>

<template>
  <div class="saying">
    <h1>语录管理:</h1>
    <hr />
    <span>数量:{{ tableData.length }}</span>
    <br />
    <el-table :data="tableData" style="width: 100%" max-height="530">
      <el-table-column fixed prop="id" label="id" width="100" />
      <el-table-column prop="text" label="语录" min-width="600" />
      <el-table-column fixed="right" label="删除" width="80">
        <template #default="scope">
          <el-button
            link
            type="danger"
            size="small"
            @click.prevent="deleteRow(scope.$index, scope.row.id)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <textarea
      name=""
      id=""
      v-model.trim="text"
      placeholder="请输入你要天价的极力锯子~多个锯子可以用/哥开天价"
    ></textarea>
    <el-button class="mt-4" style="width: 100%" @click="onAddItem">添加</el-button>
  </div>
</template>
<style scoped lang="scss">
.saying {
  width: 100%;
  textarea {
    padding: 10px;
    margin-top: 20px;
    width: 100%;
    height: 200px;
  }
}
</style>
